import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Descriptions,
  Row,
  Col
} from 'antd';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch
} from './config';

const NewForm = (props: any) => {
  const formData = [
    { name: 'batch', label: '请输入批次', message: '请输入批次' },
    { name: 'breed', label: '请输入品种', message: '请输入品种' },
    { name: 'grade', label: '请输入等级', message: '请输入等级' },
    { name: 'number', label: '请输入数量', message: '请输入数量' },
    { name: 'weight', label: '请输入重量', message: '请输入货物重量' },
    { name: 'specification', label: '请输入规格', message: '请输入规格' }
  ];
  return (
    <Form ref={props.newref} layout={'vertical'} style={{ minHeight: '100%', flex: 1, overflow: 'auto', width: '100%', overflowX: 'hidden' }}>
      <Row>
    {/* eslint-disable-next-line array-callback-return*/}
      {formData.map((item,index) => {
        // eslint-disable-next-line no-lone-blocks
        {if(index<formData.length/2){

          return(
            <Col xs={{ span: 5, offset: 2 }} lg={{ span: 8, offset: 2 }}>
              <Form.Item
                key={item.name}
                label={item.label}
                name={item.name}
                rules={[{ required: true, message: item.message }]}
              >
                <Input />
              </Form.Item>
            </Col>
          )
        } else {
          return (
            <Col xs={{ span: 5, offset: 2 }} lg={{ span: 8, offset: 2 }}>
              <Form.Item
                key={item.name}
                label={item.label}
                name={item.name}
                rules={[{ required: true, message: item.message }]}
              >
                <Input />
              </Form.Item>
            </Col>
          )
        }
      }
     } )}

      </Row>
    </Form>
  );
};

//按钮组
const Buttongroup = (props: any) => {
  return (
    <div style={{ marginBottom: 10, float: 'left' }}>
      <Button
        type="primary"
        onClick={() => props.add()}
        style={{ marginRight: 10 }}
      >
        新增日志
      </Button>
      <Button
        danger
        onClick={() => {
          props.checkIt();
        }}
        style={{ marginRight: 10 }}
      >
        批量删除
      </Button>
      <Button style={{ marginRight: 10 }}>导入</Button>
      <Button onClick={() => props.exported()}>导出</Button>
    </div>
  );
};

const Receipt = memo(() => {
  //复选框的内容设定
  const [selectionType] = useState<'checkbox' | 'radio'>('checkbox');

  //更多功能定位id
  const [Drawerid, setDrawerid]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
  const [itemSelected, setItemSelected] = useState<React.Key[]>([]);

  //是否新增
  const [edited, setEdited]: any = useState(null);
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow]: any = useState(false);
  const newref: any = useRef();
  const [dataSource, setdataSource]: any = useState([]);
  const [searchMore, setSearchMore] = useState(false);

  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);

  useEffect(() => {
    http.get('/server/dailySlaughter/list/1/10').then((res) => {
      setdataSource(res.data.records);
    });
  }, []);

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[]) => {
      setItemSelected(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };

  const checkIt = () => {
    http({
      url: `/server/dailySlaughter/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then((res) => {
      http.get('/server/dailySlaughter/list/1/10').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };

  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };
  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    //如果id存在--就是修改
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/server/dailySlaughter/update/${edited.id}`, {
          ...newedited
        })
        .then((res) => {
          // 再请求一次获得修改后的数据
          http.get('/server/dailySlaughter/list/1/10').then((res) => {
            setdataSource(res.data.records);
          });
        });
      setEdited(null);
      return;
    }
    //id不在--就是新增
    // handleAddModalOk
    // customerName numberOfPieces only weight averageWeight pickupDate pickupPerson species remark

    const measurement = newref.current.getFieldsValue();

    http
      .post('/server/dailySlaughter/save', {
        ...measurement
      })
      .then((res) => {
        http.get('/server/dailySlaughter/list/1/10').then((res) => {
          setdataSource(res.data.records);
        });
      });
  };

  //编辑
  const edit = (record: any) => {
    setAddModalVisible(true);

    //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...record
      });
      setEdited(record);
    }, 0);
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    setTimeout(() => {
      setTimeout(() => {
        newref.current.setFieldsValue({
          batch: '',
          breed: '',
          grade: '',
          number: '',
          weight: '',
          specification: ''
        });
      }, 0);
    });
    setAddModalVisible(true);
  };

  const indexTable = {
    pagination: {
      //每页10条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //当前的页数和大小
      onShowSizeChange: (current: any, pageSize: any) => {},
      //自定义每页显示项目的选项
      pageSizeOptions: ['1', '2', '3', '4', '5', '6', '8', '10'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      onShowQuickJump: (page: any) => {},
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length,
      // 改变的回调函数
      onChange: (page: any) => {}
    }
  };
  // //form batch breed grade number weight specification

  const FormColumns: any = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '批次编号',
      dataIndex: 'batch',
      key: 'batch',
      width: 100
    },

    {
      title: '品种',
      dataIndex: 'breed',
      key: 'breed'
    },
    {
      title: '等级',
      dataIndex: 'grade',
      key: 'grade'
    },
    {
      title: '数量',
      dataIndex: 'number',
      key: 'number'
    },

    {
      title: '规格',
      dataIndex: 'specification',
      key: 'specification'
    },
    {
      title: '重量（kg）',
      dataIndex: 'weight',
      key: 'weight'
    },

    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            // cancelButtonProps={{ size: 'middle' }}
            onConfirm={() => {
              http
                .delete(`/server/dailySlaughter/delete/${record.id}`)
                .then((res) => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setdataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];

  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={(e) => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },

        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );

  // 高级检索 条件查询 /server/feeVoucherSlaughter/get

  const onFinish = (form: any) => {
    if (Object.keys(form).length === 0) {
      http.get('/server/dailySlaughter/list/1/10').then((res) => {
        setdataSource(res.data.records);
      });
      return;
    }
    http
      .post('/server/dailySlaughter/conditionGet/1/10', form)
      .then((res: any) => {
        if (res.statusCode !== 20000) {
          return message.error('查询失败');
        }
        const data = res.data.records || [];
        setdataSource(data);
      });
  };
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http.get(`/server/dailySlaughter/get/${data.id}`).then((res) => {
      setDrawerid(res.data);
    });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };

  const renderDescriptionsItem = () => {
    const descriptions = [
      { label: '订单编号', key: 'id' },
      { label: '客户名', key: 'customerName' },
      { label: '货物毛重', key: 'weight' },
      { label: '货物件数', key: 'numberOfPieces' },
      { label: '货物只数', key: 'only' },
      { label: '提货人', key: 'pickupPerson' },
      { label: '提货日期', key: 'pickupDate' },
      { label: '品种', key: 'species' }
    ];
    return descriptions.map((item) => (
      <Descriptions.Item label={item.label} key={item.key}>
        {Drawerid[item.key]}
      </Descriptions.Item>
    ));
  };

  return (
    <DivWrapper>
      {searchMore && (
        <div>
          <ProForm formItems={PageSearchConfig} onFinish={onFinish} />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      )}
      <Buttongroup
        checkIt={() => checkIt()}
        add={() => add()}
        exported={() => exported()}
      />
      <UseSearch
        setisMoreSearchShow={(e: any) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      />
      <SearchSelector
        dataSource={(e: any) => setdataSource(e)}
        style={{ float: 'right' }}
      />

      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i) => i.id}
          rowSelection={{
            type: selectionType,
            ...rowSelection
          }}
        />
      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        {/* 订单编号，客户名 创建时间  件数 只数 重量 提货日期 提货人 */}
        <Descriptions
          title={`客户名：${Drawerid.customerName}`}
          bordered
          style={{ width: '450px' }}
        >
          {renderDescriptionsItem()}
        </Descriptions>
      </Drawer>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column-reverse',

        }}
        title="新增日志"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref} />
      </Modal>
    </DivWrapper>
  );
});
export default Receipt;
